package com.bcxk.order.scheduling;

import com.bcxk.entity.dto.Cron;
import com.bcxk.order.redis.RedisService;
import com.bcxk.service.CronService;
import com.bcxk.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashSet;

/**
 * @author NieMingkun
 */
@Configuration
@EnableScheduling
public class TimeTasks implements SchedulingConfigurer {
    static String cron;
    @Autowired
    CronService cronService;
    @Autowired
    RedisService redisService;
    @Autowired
    OrderService orderService;




    public static void setCron(String cron) {
        TimeTasks.cron = cron;
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        Cron crons = cronService.getCron(1L);
        cron=crons.getCron();
        Runnable task = new Runnable() {
            @Override
            public void run() {
                //任务逻辑代码部分.
                System.err.println("定时任务执行中！"+ new Date());
                LinkedHashSet set= (LinkedHashSet) redisService.getAll();
                ArrayList<String> list = new ArrayList<>(set);
                StringBuffer stringBuffer =new StringBuffer();
                Iterator iterator =list.iterator();
                while(iterator.hasNext()){
                    stringBuffer.append(iterator.next()+",");
                }
                stringBuffer.append(0);
                //当不为空时 连接数据库修改数据
                    orderService.orderUpdate(stringBuffer.toString());


            }
        };
        Trigger trigger = new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                //任务触发，可修改任务的执行周期.
                CronTrigger trigger = new CronTrigger(cron);
                Date nextExec = trigger.nextExecutionTime(triggerContext);
                return nextExec;
            }

        };
        scheduledTaskRegistrar.addTriggerTask(task, trigger);

    }
}
